package ThreadDemo.ThreadDemo6;

import java.util.Scanner;

public class Demo4 {

}




class Counter {
    public int count = 0;

    // 方法这边又加上锁了
    public void add() {
        synchronized (this) {
            count++;
        }
    }

}

 class Demo10 {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();

        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
//                方法的外面加上了锁
                synchronized (counter) {
                    counter.add();
                }
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                synchronized (counter) {
                    counter.add();
                }
            }
        });

        t1.start();
        t2.start();
        t1.join();
        t2.join();

        System.out.println("counter=" + counter.count);

    }
}


 class Demo17 {
    private static Object locker1 = new Object();
    private static Object locker2 = new Object();

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            synchronized (locker1) {
                System.out.println("t1 加锁 locker1 完成");

                // 这里的 sleep 是为了确保, t1 和 t2 都先分别拿到 locker1 和 locker2 然后在分别拿对方的锁.
                // 如果没有 sleep 执行顺序就不可控, 可能出现某个线程一口气拿到两把锁, 另一个线程还没执行呢, 无法构造出死锁.
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

                synchronized (locker2) {
                    System.out.println("t1 加锁 locker2 完成");
                }
            }
        });

        Thread t2 = new Thread(() -> {
            synchronized (locker1) {
                System.out.println("t2 加锁 locker1 完成");

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

                synchronized (locker2) {
                    System.out.println("t2 加锁 locker2 完成");
                }
            }
        });

        t1.start();
        t2.start();
    }
}


// 啥都不写
//                try {
//                    Thread.sleep(10);
//                } catch (InterruptedException e) {
//                    throw new RuntimeException(e);
//                }







class Demo18 {
    private volatile static  int n = 0;

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {

            while (n == 0) {

            }
            System.out.println("t1 线程结束循环");
        });

        Thread t2 = new Thread(() -> {

            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入一个整数: ");
            n = scanner.nextInt();
        });

        t1.start();
        t2.start();

        t1.join();

    }
}